import traceback
import pyautogui
import os
import time
import pyperclip as clip
import json
import pandas as pd
import datetime
from sqlalchemy import create_engine
from jsjj.util.dbUtil import *
from jsjj.util.emailUtil import *
from jsjj.util.logUtil import *
from jsjj.util.timeUtil import *
from jsjj.util.mouseMoveUtil import *
import math

runMode = '日模式'                  #一个日历，还要理解这个日历实际的使用方式
# 拼多多-商家后台-流量数据-营销活动数据-商品数据
modeName = '拼多多_商家后台_流量数据_营销活动数据_商品数据详情'
# 左边点击，直到点击到一级类目，该过程不参与循环
def SPGK(engine, conn):
    # 关闭电霸每天晚上会弹出的一个屏蔽页面
    pyautogui.FAILSAFE = False

    # 菜单看不到，因此要移动一下才能看到
    sleep(6)

    # 左边--【物流工具】
    viaCommonUrl('https://mms.pinduoduo.com/orders/order/carriage/list')

    sleep(4)
    pyautogui.keyDown('f12')
    pyautogui.keyUp('f12')

    # 左边--【流量数据】
    viaCommonUrl('https://mms.pinduoduo.com/sycm/search_data/plate')

    jsonFromWebShopName = getSjhtShopName()

    # 【营销活动数据】
    pyautogui.moveTo(675, 232, 6)
    pyautogui.click()

    # 获取活动类型下拉框（暂时不获取了，定为4个，变了后续再修改）
    activityTypeNameObj = ''
    for i in range(1, 5):

        # 滚到顶部
        pyautogui.moveTo(715, 876, 2)

        sleep(2)
        pyautogui.scroll(10000)

        # 清空network
        pyautogui.moveTo(1541, 144, 6)
        pyautogui.click()

        if i == 1:
            activityTypeNameObj = '限量折扣'
            pyautogui.moveTo(465, 345, 6)
            pyautogui.click()

            sleep(6)
            pyautogui.moveTo(465, 379)
            pyautogui.click()

        elif i == 2:
            activityTypeNameObj = '领券中心'
            pyautogui.moveTo(465, 345, 6)
            pyautogui.click()

            pyautogui.moveTo(465, 407, 6)
            pyautogui.click()
        elif i == 3:
            activityTypeNameObj = '个性化首页'

            pyautogui.moveTo(465, 345, 6)
            pyautogui.click()

            pyautogui.moveTo(465, 433, 6)
            pyautogui.click()
        else:
            activityTypeNameObj = '限时秒杀'

            pyautogui.moveTo(465, 345, 6)
            pyautogui.click()

            pyautogui.moveTo(465, 462, 6)
            pyautogui.click()

        # 点击查询
        pyautogui.moveTo(666, 345, 6)
        pyautogui.click()

        # ==============F12的filter过滤框
        pyautogui.moveTo(1571, 167, 6)
        pyautogui.doubleClick()

        # 过滤
        clip.copy('queryMallActivityOverView')  # 先复制
        pyautogui.hotkey('ctrl', 'v')  # 再粘贴

        # 选中过滤文件
        pyautogui.moveTo(1540, 325, 6)
        pyautogui.click()

        # 点中json值区域
        pyautogui.moveTo(1812, 497, 6)
        pyautogui.click()

        sleep(2)
        pyautogui.hotkey('ctrl', 'a')

        sleep(2)
        pyautogui.hotkey('ctrl', 'c')

        # 读取剪切板内容queryGoodsPageRT
        sleep(2)
        value = clip.paste()
        jsonFromWeb1 = json.loads(value)

        # ==============F12的filter过滤框
        pyautogui.moveTo(1571, 167, 6)
        pyautogui.doubleClick()

        # 过滤
        clip.copy('queryMallActivityGoodsList')  # 先复制
        pyautogui.hotkey('ctrl', 'v')  # 再粘贴

        # 选中过滤文件（第1个文件才是对的）
        pyautogui.moveTo(1539, 325, 6)
        pyautogui.click()

        # 点中json值区域
        pyautogui.moveTo(1812, 497, 6)
        pyautogui.click()

        sleep(2)
        pyautogui.hotkey('ctrl', 'a')

        sleep(2)
        pyautogui.hotkey('ctrl', 'c')

        # 读取剪切板内容
        sleep(2)
        value = clip.paste()
        jsonFromWeb2 = json.loads(value)

        jsonDf = {'guv': [jsonFromWeb1['result']['guv']],
                  'gpv': [jsonFromWeb1['result']['gpv']],
                  'vstGoodsCnt': [jsonFromWeb1['result']['vstGoodsCnt']],
                  'cfmOrdrAmt': [jsonFromWeb1['result']['cfmOrdrAmt']],
                  'goodsFavClkCnt': [jsonFromWeb1['result']['goodsFavClkCnt']],
                  'cfmOrdrGoodsQty': [jsonFromWeb1['result']['cfmOrdrGoodsQty']],
                  'guvPct': [jsonFromWeb1['result']['guvPct']],
                  'gpvPct': [jsonFromWeb1['result']['gpvPct']],
                  'vstGoodsCntPct': [jsonFromWeb1['result']['vstGoodsCntPct']],
                  'cfmOrdrAmtPct': [jsonFromWeb1['result']['cfmOrdrAmtPct']],
                  'goodsFavClkCntPct': [jsonFromWeb1['result']['goodsFavClkCntPct']],
                  'cfmOrdrGoodsQtyPct': [jsonFromWeb1['result']['cfmOrdrGoodsQtyPct']],
                  'guvIsPercent': [jsonFromWeb1['result']['guvIsPercent']],
                  'gpvIsPercent': [jsonFromWeb1['result']['gpvIsPercent']],
                  'vstGoodsCntIsPercent': [jsonFromWeb1['result']['vstGoodsCntIsPercent']],
                  'cfmOrdrAmtIsPercent': [jsonFromWeb1['result']['cfmOrdrAmtIsPercent']],
                  'goodsFavClkCntIsPercent': [jsonFromWeb1['result']['goodsFavClkCntIsPercent']],
                  'cfmOrdrGoodsQtyIsPercent': [jsonFromWeb1['result']['cfmOrdrGoodsQtyIsPercent']],
                  'activityTypeName': [activityTypeNameObj]
                  }
        df = pd.read_json(json.dumps(jsonDf))
        df['statDate'] = datetime.datetime.now()
        df['shopName'] = jsonFromWebShopName['result']['username']
        df['运行模式'] = runMode
        df['统计月'] = ''
        df['统计周'] = ''
        df['统计日'] = ''
        df['统计日周月'] = ''
        df['插入时间'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        if runMode == '月模式':
            df['统计月'] = str(datetime.datetime.now().month - 1) + "月"
            df['统计日周月'] = df['统计月']
        if runMode == '周模式':
            df['统计周'] = getLastWeekOfYear(datetime.datetime.now().year, datetime.datetime.now().month,
                                          datetime.datetime.now().day)
            df['统计日周月'] = df['统计周']
        if runMode == '日模式':
            df['statDate'] = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime(
                "%Y-%m-%d")
            df['统计日'] = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime(
                "%Y-%m-%d %H:%M:%S")  # 减一天，统计的是昨天的数据
            df['统计日周月'] = df['统计日']
        # 解决可能出现的超时问题bugfix 2020.08.18
        conn.connection.connection.ping(reconnect=True)
        df.to_sql(name='拼多多_商家后台_流量数据_营销活动数据_商品数据', con=conn, if_exists='append', index=False)

        # 第一页的保存
        dfLoop = pd.read_json(json.dumps(jsonFromWeb2['result']['mallActivityVOList']))
        dfLoop['statDate'] = datetime.datetime.now()
        dfLoop['shopName'] = jsonFromWebShopName['result']['username']

        dfLoop['运行模式'] = runMode
        dfLoop['统计月'] = ''
        dfLoop['统计周'] = ''
        dfLoop['统计日'] = ''
        dfLoop['统计日周月'] = ''
        dfLoop['插入时间'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if runMode == '月模式':
            dfLoop['统计月'] = str(datetime.datetime.now().month - 1) + "月"
            dfLoop['统计日周月'] = dfLoop['统计月']
        if runMode == '周模式':
            dfLoop['统计周'] = getLastWeekOfYear(datetime.datetime.now().year, datetime.datetime.now().month,
                                          datetime.datetime.now().day)
            dfLoop['统计日周月'] = dfLoop['统计周']
        if runMode == '日模式':
            dfLoop['统计日'] = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime(
                "%Y-%m-%d %H:%M:%S")  # 减一天，统计的是昨天的数据
            dfLoop['统计日周月'] = dfLoop['统计日']
        # 解决可能出现的超时问题bugfix 2020.08.18
        conn.connection.connection.ping(reconnect=True)
        dfLoop.to_sql(name='拼多多_商家后台_流量数据_营销活动数据_商品数据详情', con=conn, if_exists='append', index=False)
        # 循环保存后面的页面（通过点击页面的下一页）
        for iLoop in range(2, math.ceil(jsonFromWeb2['result']['totalNum'] / 10) + 2):

            pyautogui.moveTo(715, 876, 6)

            sleep(2)
            pyautogui.scroll(-10000)

            # 清空network
            pyautogui.moveTo(1541, 144, 6)
            pyautogui.click()

            # 点击【下一页】 ，位置会变的？？
            pyautogui.moveTo(1371, 940, 6)
            pyautogui.click()

            # ==============F12的filter过滤框
            pyautogui.moveTo(1571, 167, 6)
            pyautogui.doubleClick()

            # 过滤
            clip.copy('queryMallActivityGoodsList')  # 先复制
            pyautogui.hotkey('ctrl', 'v')  # 再粘贴

            # 选中过滤文件
            pyautogui.moveTo(1540, 325, 6)
            pyautogui.click()

            # 点中json值区域
            pyautogui.moveTo(1812, 497, 6)
            pyautogui.click()

            sleep(2)
            pyautogui.hotkey('ctrl', 'a')

            sleep(2)
            pyautogui.hotkey('ctrl', 'c')

            # 读取剪切板内容queryGoodsPageRT
            sleep(2)
            value = clip.paste()
            jsonFromWebLoop_StartFromPage2 = json.loads(value)

            dfLoopInner = pd.read_json(json.dumps(jsonFromWebLoop_StartFromPage2['result']['mallActivityVOList']))
            dfLoopInner['statDate'] = datetime.datetime.now()
            dfLoopInner['shopName'] = jsonFromWebShopName['result']['username']

            dfLoopInner['运行模式'] = runMode
            dfLoopInner['统计月'] = ''
            dfLoopInner['统计周'] = ''
            dfLoopInner['统计日'] = ''
            dfLoopInner['统计日周月'] = ''
            dfLoopInner['插入时间'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            if runMode == '月模式':
                dfLoopInner['统计月'] = str(datetime.datetime.now().month - 1) + "月"
                dfLoopInner['统计日周月'] = dfLoopInner['统计月']
            if runMode == '周模式':
                dfLoopInner['统计周'] = getLastWeekOfYear(datetime.datetime.now().year, datetime.datetime.now().month,
                                              datetime.datetime.now().day)
                dfLoopInner['统计日周月'] = dfLoopInner['统计周']
            if runMode == '日模式':
                dfLoopInner['统计日'] = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime(
                    "%Y-%m-%d %H:%M:%S")  # 减一天，统计的是昨天的数据
                dfLoopInner['统计日周月'] = dfLoopInner['统计日']
            # 解决可能出现的超时问题bugfix 2020.08.18
            conn.connection.connection.ping(reconnect=True)
            dfLoopInner.to_sql(name='拼多多_商家后台_流量数据_营销活动数据_商品数据详情', con=conn, if_exists='append', index=False)

    resetGuiAtLastStepCloseF12ToTop()

    return


def executeCatchWeb(engine, conn):
    try:
        LogTaskAndMachine('拼多多_商家后台_流量数据_营销活动数据_商品数据详情', engine, conn, '', runMode)
        SPGK(engine, conn)
    except Exception as e:
        traceback.print_exc()
        sendAlert('【异常中断】' + modeName, '异常:' + str(e) + '|报错文件:' + os.path.split(__file__)[-1], engine, conn)
        print('【异常中断】' + modeName, '异常:' + str(e) + '|报错文件:' + os.path.split(__file__)[-1])
        return
    sendFinalSuccessEmail('●正常完成●' + modeName, '', engine, conn, modeName, runMode)


if __name__ == '__main__':
    engine, conn = getConn()
    executeCatchWeb(engine, conn)
